# -*- coding: utf-8 -*-
import functools
from datetime import datetime
import json

# 风险阈值秒
RISK_SECONDS = 10
# 风险次数阈值
RISK_NUMBER = 10

TIME_FORMAT = '%Y-%m-%d %H:%M:%S'


# str转换到datatime
def str_to_date(str):
    return datetime.strptime(str, TIME_FORMAT)


# 计算时间差 秒
def get_time_difference_seconds(big_date, small_date):
    return (str_to_date(big_date) - str_to_date(small_date)).seconds


# 验证码发送风险拦截
def risk_send_email_captcha(method):
    @functools.wraps(method)
    async def wrapper(self, *args, **kwargs):
        email = self.email
        now_time = str(datetime.now().strftime(TIME_FORMAT))
        cache = self.cache_action.risk_email().get(email)
        if cache:
            # 非首次请求
            cache_data = json.loads(cache)
            number = cache_data['number']
            creation_time = cache_data['creation_time']
            finally_time = cache_data['finally_time']

            time_difference_seconds = get_time_difference_seconds(
                now_time, finally_time)

            time_difference_hour = get_time_difference_seconds(
                now_time, creation_time) / (24 * 60 * 60)

            value = {
                'email': email,
                'number': number + 1,
                'creation_time': creation_time,
                'finally_time': now_time,
            }

            # 拦截规则
            if time_difference_seconds < RISK_SECONDS:
                return self.render_json(-1, '请求过于频繁, 已被系统终止')
            elif time_difference_hour < 24 and number > RISK_NUMBER:
                return self.render_json(-1, '超过单日发送次数')

        else:
            # 首次请求
            value = {
                'email': email,
                'number': 1,
                'creation_time': now_time,
                'finally_time': now_time,
            }

        self.cache_action.risk_email().set(email, json.dumps(value))
        await method(self, *args, **kwargs)

    return wrapper